<template>
  <div class="history-data">
    <div class="content-left">
      <div class="left-item">
        <div class="title-font">数据导入区</div>
        <div class="import-content">
          <div class="upload-status">
            是否已经上传负荷历史数据：<span
              :style="{ color: isUpload.loadHistory ? 'green' : 'red' }"
              >{{ isUpload.loadHistory ? "是" : "否" }}
            </span>
          </div>
          <div class="upload-status">
            是否已经上传气象历史数据 ：<span
              :style="{ color: isUpload.weatherHistory ? 'green' : 'red' }"
              >{{ isUpload.weatherHistory ? "是" : "否" }}</span
            >
          </div>
          <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :http-request="uploadFileRequest"
            :data="{ type: 'load_file' }"
          >
            <template #trigger>
              <el-button class="import-button" type="primary"
                >导入历史负荷数据
              </el-button>
            </template>
          </el-upload>
          <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :http-request="uploadFileRequest"
            :data="{ type: 'weather_file' }"
          >
            <template #trigger>
              <el-button class="import-button" type="primary"
                >导入历史气象数据
              </el-button>
            </template>
          </el-upload>
        </div>
      </div>
      <!-- <div class="left-item">
        <div class="title-font">参数设置区</div>
        <div class="import-content">
          <el-form>
            <el-form-item label="开始时间：">
              <el-date-picker
                v-model="paramsForm.startTime"
                type="date"
                placeholder="选择开始时间"
                :disabled-date="disabledStartDate"
              />
            </el-form-item>
            <el-form-item label="终止时间：">
              <el-date-picker
                v-model="paramsForm.endTime"
                type="date"
                placeholder="选择终止时间"
                :disabled-date="disabledEndDate"
              />
            </el-form-item>
            <el-form-item label="日负荷采集次数：">
              <el-input
                v-model="paramsForm.times"
                placeholder="请输入采集次数"
              />
            </el-form-item>
          </el-form>
          <el-button class="import-button" type="primary">模型训练 </el-button>
        </div>
      </div> -->
      <div class="left-item">
        <div class="title-font">模型训练区</div>
        <div class="import-content">
          <div class="model-font">基于历史数据负荷预测</div>
          <div class="upload-status">
            是否已经进行了模型训练：<span
              :style="{ color: isUpload.modelTrain ? 'green' : 'red' }"
              >{{ isUpload.modelTrain ? "是" : "否" }}</span
            >
          </div>
          <el-button
            @click="getAnalysisTrain"
            class="import-button"
            type="primary"
            >模型训练
          </el-button>
        </div>
      </div>
    </div>
    <div class="content-right">
      <div class="chart-content">
        <div class="chart-top">
          <!-- <div class="choose-date">
            <div class="picker-label">选择日期:</div>
            <el-date-picker
              v-model="chooseDate"
              type="date"
              placeholder="选择时间"
              :disabled-date="disabledDateArea"
            />
            <el-button type="primary">搜索</el-button>
          </div> -->
        </div>
        <div class="charts">
          <div class="button-area">
            <div
              class="load-button"
              :class="btnType == item.type ? 'active' : ''"
              type="primary"
              v-for="(item, index) in buttonList"
              :key="item.type"
              @click="avangeClick(item)"
            >
              {{ item.name }}
            </div>
          </div>
          <Echarts
            v-if="chartData.xData.length > 0 && btnType != 'correlation'"
            :chartData="chartData"
            :chartId="'load'"
          ></Echarts>

          <barChart
            v-if="btnType == 'correlation'"
            :chartData="chartData"
            :chartId="'barChart'"
          ></barChart>
        </div>
      </div>
      <div class="chart-content">
        <div class="table-font">结果展示</div>
        <ElTable
          style="height: 90%"
          :tableData="tableData"
          :tableColumns="tableColumns"
        ></ElTable>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Echarts from "@/components/charts/echarts.vue";
import barChart from "./components/barChart.vue";
import ElTable from "@/components/table.vue";
import {
  dataAnalysis,
  analysisAverage,
  uploadFile,
  historyState,
  analysisTrain,
} from "@/api/index.js";

const paramsForm = ref({
  startTime: "",
  endTime: "",
  times: "",
});

const buttonList = ref([
  {
    name: "历史负荷曲线",
    type: "history",
  },
  {
    name: "月平均负荷",
    type: "month",
  },
  {
    name: "周平均负荷",
    type: "week",
  },
  {
    name: "日平均负荷",
    type: "day",
  },
  {
    name: "相关性计算",
    type: "correlation",
  },
]);
const btnType = ref("history");

const isUpload = ref({
  weatherHistory: false, //是否已经上传气象历史数据
  loadHistory: false, //是否已经上传负荷历史数据
  modelTrain: false, //是否已经进行了模型训练
});
const getHistoryState = () => {
  historyState().then((res) => {
    if (res.code == 200) {
      isUpload.value.loadHistory = res.load_state;
      isUpload.value.weatherHistory = res.weather_state;
      isUpload.value.modelTrain = res.model_state;
    }
  });
};

const chooseDate = ref(""); //选择的具体某一天
const disabledDateArea = (time) => {
  return (
    time.getTime() < paramsForm.value.startTime ||
    time.getTime() > paramsForm.value.endTime
  );
};

const avangeClick = (param) => {
  switch (param.type) {
    case "history":
      // 处理 'history' 情况
      getHistoryData();
      btnType.value = param.type;
      break;
    default:
      // 处理其他情况
      analysisAverageData(param.type);
      break;
  }
  chartData.value.name = param.name;
};

const chartUrl = ref("");
const getHistoryData = () => {
  dataAnalysis().then((res) => {
    if (res.code == 200) {
    }
  });
};
//月，周，日,相关性平均负荷曲线
const analysisAverageData = (type) => {
  analysisAverage(type).then((res) => {
    if (res.code == 200) {
      if (type != "correlation") {
        chartData.value.xData = res.times;
        chartData.value.yData = res.data;
        let params = {
          times: res.times,
          data: res.data,
        };
        detailTableData(type, params, res.times.length);
      } else {
        let data = res.data;
        const keys = Object.keys(data); // 提取键
        const values = Object.values(data);
        chartData.value.xData = keys;
        chartData.value.yData = values;
        tableColumns.value = [];
        tableData.value = [];
        let tableItem = {};
        keys.map((item, index) => {
          tableColumns.value.push({ prop: item, label: item });
          tableItem[item] = values[index];
        });
        tableData.value.push(tableItem);
      }
      btnType.value = type;
    }
  });
};

//echarts图表数据
const chartData = ref({
  xData: [],
  yData: [],
  name: "",
});
// 上传文件
const uploadFileRequest = (param) => {
  let formData = new FormData();
  if (param.data.type == "load_file") {
    formData.append("load", param.file);
  } else {
    formData.append("weather", param.file);
  }
  console.log(formData.get("load"), "formData");
  let params = {
    type: param.data.type,
    formData,
  };
  uploadFile(params).then((res) => {
    if (res.code == 200) {
      ElMessage.success("上传成功");
      getHistoryState();
    }
  });
};

const tableColumns = ref([]);
const tableData = ref([]);

//处理页面上要显示的表格数据
const detailTableData = (type, data, dataLength) => {
  // 检查 data 参数是否包含必要的属性
  if (!data || !data.times || !data.data) {
    console.error("Invalid data object provided");
    return;
  }

  // 定义一个映射关系，避免重复代码
  const typeMapping = {
    month: { prop: "month", label: "月份" },
    week: { prop: "week", label: "日期" },
    day: { prop: "day", label: "日期" },
  };

  // 如果传入的 type 无效，直接返回
  const columnConfig = typeMapping[type];
  if (!columnConfig) {
    console.error("Invalid type provided");
    return;
  }

  // 设置表格列
  tableColumns.value = [
    { prop: columnConfig.prop, label: columnConfig.label },
    { prop: "average", label: `${columnConfig.label}平均负荷` },
  ];

  // 使用 map 生成表格数据
  tableData.value = Array.from({ length: dataLength }, (_, index) => ({
    [columnConfig.prop]: data.times[index],
    average: data.data[index],
  }));
};
//训练模型
const getAnalysisTrain = () => {
  analysisTrain().then((res) => {
    if (res.code == 200) {
      ElMessage.success("训练完成");
      isUpload.value.modelTrain = true;
    }
  });
};
onMounted(() => {
  // console.log("Component mounted");
  getHistoryState();
  getHistoryData();
});
</script>
<style lang="scss" scoped>
@import "@/global.scss";
@import "@/common/table.scss";
.history-data {
  width: 100%;
  height: 100%;
  display: flex;
  .content-left {
    // flex: 1;
    width: vw(400);
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-left: 1px solid #818181;

    .left-item {
      width: 100%;
      flex: 1;
      box-sizing: border-box;
      padding: 20px;
      border-bottom: 1px solid #818181;
      border-right: 1px solid #818181;
      .import-content {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
      .import-button {
        width: vw(240);
      }
    }
    .left-item:last-child {
      border-bottom: 0;
    }
    .title-font {
      font-size: 20px;
      color: #fff;
      font-weight: 500;
      font-family: Georgia, "Times New Roman", Times, serif;
    }
    .model-font {
      font-size: 20px;
      color: #fff;
      font-weight: 500;
      font-family: Georgia, "Times New Roman", Times, serif;
      margin-bottom: 20px;
    }
    .upload-status {
      margin: 10px;
    }
  }
  .content-right {
    // flex: 3.5;
    width: calc(100% - vw(400));
    overflow: hidden;
    height: 100%;
    border-right: 1px solid #818181;
    .button-area {
      width: auto;
      height: calc(100% - vh(100));
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      gap: vh(10);
    }
    .chart-content {
      width: 100%;
      // height: calc((100vh - vh(130)) / 2);
      height: calc((100vh - vh(100)) / 2);
      border-top: 1px solid #818181;
      padding: vh(10) vw(20);
      box-sizing: border-box;
    }
    .chart-content:first-child {
      border-top: 0;
    }
    .chart-button {
      width: vw(240);
    }
    .load-button {
      min-width: vw(100);
      padding: vw(10);
      font-size: 14px;
      border-radius: 4px;
      text-align: center;
      cursor: pointer;
      background-color: #ecf5ff;
      color: #409eff;
      &:hover {
        background-color: #409eff;
        color: #ecf5ff;
      }
    }
    // .load-button:hover {
    //   background-color: #409eff;
    //   color: #ecf5ff;
    // }
    .active {
      background-color: #409eff;
      color: #ecf5ff;
    }
    .chart-top {
      width: 100%;
      height: vh(50);
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      font-size: vw(16);
    }
    .choose-date {
      display: flex;
      align-items: center;
      gap: vw(10);
    }
    .chart-style {
      width: 100%;
      // height: vh(400);
      height: auto;
    }
    .table-font {
      color: aqua;
      font-size: 16px;
      margin-bottom: 14px;
    }

    .charts {
      width: 100%;
      display: flex;
      height: vh(440);
      overflow: hidden;
    }
    .chart-img {
      // width: vw(900);
      // height: vh(400);
      // transform: scale(0.8);
      object-fit: cover;
      max-width: 100%;
      height: 100%;
    }
  }
}
:deep(.el-form-item__label) {
  color: #fff;
  font-size: 15px;
}
.el-button + .el-button {
  margin-left: 0;
}
</style>
